package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("/goods/")//定义url中的共性部分
public class GoodsController{
    @Autowired
    private GoodsService goodsService;

    //@ExceptionHandler 描述的为一个controller中的异常处理方法
    //RuntimeException.class 为当前方法可以处理的异常类型
//    @ExceptionHandler(RuntimeException.class)
//    @ResponseBody
//    public String doHandleRuntimeException(RuntimeException e){
//        log.error("GoodsController.exception {}",e.getMessage());
//        return e.getMessage();
//    }

    @GetMapping("doFindById/{id}")
    public String doFindById(@PathVariable Integer id, Model model){
        Goods goods=goods = goodsService.findById(id);
        model.addAttribute("goods", goods);
        return "goods-update";
    }


    @RequestMapping("doUpdateGoods")
    public String doUpdateGoods(Goods goods,Model model){
        goodsService.updateGoods(goods);
//        List<Goods> list= goodsService.findGoods(null);
//        model.addAttribute("list", list);
//        return "goods";
        return "redirect:/goods/doFindGoods";
    }
    @PostMapping("doSaveGoods")
    public String doSaveGoods(Goods goods,Model model){
        goodsService.saveGoods(goods);
//        List<Goods> list= goodsService.findGoods(null);
//        model.addAttribute("list", list);
//        return "goods";
        //重定向(从客户端向服务端再次发起新的请求)
        return "redirect:/goods/doFindGoods";
    }

    /**响应一个商品添加页面*/
    @GetMapping("doGoodsAddUI")
    public String doGoodsAddUI(){
        return "goods-add";
    }

    @RequestMapping("doDeleteById")
    public String doDeleteById(Integer id,Model model){
        goodsService.deleteById(id);
//       List<Goods> list=goodsService.findGoods(null);
//        model.addAttribute("list", list);
//        return "goods";
        return "redirect:/goods/doFindGoods";
    }

    @GetMapping("doFindGoods")
    public String doFindGoods(String name,Model model){
        List<Goods> list = goodsService.findGoods(name);
        //lambda,方法引用
        //list.forEach(System.out::println);
//        for(Goods g:list){
//            System.out.println(g);
//        }
        model.addAttribute("list", list);
        return "goods";//viewname
    }
}
